package com.me.forum.service;

import com.me.forum.dao.IUserDao;
import com.me.forum.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

@Service
public class UserProcessService implements UserDetailsService {
	@Autowired
	private IUserDao userdao;
	
	@Autowired
	private PasswordEncoder encoder;
	
	@Autowired
	private HttpSession session;
	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		User user = userdao.findUserByUsername(username);
		
		if (user == null) {
			throw new UsernameNotFoundException(username);
		}
		
		session.setAttribute("user",user);
		
		return new org.springframework.security.core.userdetails.User(
			user.getUsername(),
			encoder.encode(user.getPassword()),
			AuthorityUtils.commaSeparatedStringToAuthorityList(user.getUsername())
		);
	}
}
